package com.spark.market.common.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class ApplicationConfig{

    @Bean("myInterceptor")
    public ApplicationInterceptor applicationInterceptor(){
        return new ApplicationInterceptor();
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        /**
         * 注意addCorsMappings后于addInterceptors执行，它会导致跨域请求失败
         */
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                InterceptorRegistration ir = registry.addInterceptor(applicationInterceptor());
                ir.addPathPatterns("/order/**");
            }
        };
    }

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");//开放哪些ip、端口、域名的访问权限// SpringBoot2.4.0 [allowedOriginPatterns]代替[allowedOrigins]
        config.setAllowCredentials(true);//是否允许发送Cookie信息
        config.addAllowedMethod("*"); //开放哪些Http方法，允许跨域访问
        config.addAllowedHeader("*"); //允许HTTP请求中的携带哪些Header信息
        config.addExposedHeader("*"); //暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }

}
